<?php

namespace App\Http\Requests\AddressController;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Overtrue\EasySms\PhoneNumber;

class AddAddressRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'coin_id' => ['required', 'exists:coins,id'],
            'note' => [
                'required',
                Rule::unique('trading_addresses')
                    ->where('user_id', $this->user()->id)
                    ->where('coin_id', $this->input('coin_id'))
            ],
            'address' => [
                'required',
                'wallet_address:'.$this->input('coin_id'),
                Rule::unique('trading_addresses')
                    ->where('user_id', $this->user()->id)
                    ->where('coin_id', $this->input('coin_id')),
            ],
//            'email_code' => [
//                'required',
//                'emailCode:'.Auth::user()->email
//            ],
        ];

        $user = auth()->user();
        if ($user->mobile) { // 短信验证码
            $area = $user->area ?: '86';
            $rules['email_code'] = [
                'required',
                'smsCode:'.(new PhoneNumber($user->mobile, $area))->getUniversalNumber(),
            ];
        } else { // 邮箱验证码
            $rules['email_code'] = [
                'required',
                'emailCode:'.$user->email
            ];
        }

        return $rules;
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'coin_id.required' => __('币种ID必填'),
            'coin_id.exists' => __('币种ID不存在'),
            'note.required' => __('钱包名称不能为空'),
            'note.unique' => __('钱包名称已经存在'),
            'email_code.required' => __('验证码必填'),
        ];
    }
}
